<template>
  <el-container class="team-applicant-container">
    <!-- 侧边栏 -->
    <el-aside class="sidebar">
      <div class="logo-container">
        <h2 class="app-title">团队选择</h2>
      </div>
      <el-menu
        :default-active="activeSection"
        @select="activeSection = $event"
        class="menu"
      >
        <el-menu-item index="leaders">
          <el-icon><UserFilled /></el-icon>
          <span>选择组长</span>
        </el-menu-item>
        <el-menu-item index="members">
          <el-icon><User /></el-icon>
          <span>本组成员</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 右侧内容区 -->
    <el-main class="content">
      <div class="board">
        <!-- 查看组长页面 -->
        <div v-if="activeSection === 'leaders'" class="section">
          <div class="section-header">
            <h2>组长列表</h2>
            <el-input
              v-model="searchQuery"
              placeholder="搜索组长"
              prefix-icon="el-icon-search"
              clearable
              class="search-input"
            ></el-input>
          </div>
          
          <el-empty v-if="leaders.length === 0" description="暂无组长数据" />
          
          <div v-else class="leader-grid">
            <el-card
              v-for="leader in filteredLeaders"
              :key="leader.user_id"
              class="leader-card"
              :body-style="{ padding: '0px' }"
              shadow="hover"
            >
              <div class="leader-card-header">
                <div class="avatar-container">
                  <el-avatar :size="64" icon="el-icon-user-solid">{{ leader.username.charAt(0) }}</el-avatar>
                </div>
                <div class="leader-info">
                  <h3>{{ leader.username }}</h3>
                  <div class="leader-tags">
                    <el-tag size="small" effect="plain" type="success">组长</el-tag>
                    <el-tag size="small" effect="plain" type="info" v-if="leader.times > 5">经验丰富</el-tag>
                  </div>
                </div>
              </div>
              
              <div class="leader-card-body">
                <div class="ability-preview">
                  <div class="ability-item">
                    <span class="ability-label">能力值</span>
                    <el-progress :percentage="leader.ability || 0" :format="format" :stroke-width="8" status="success"></el-progress>
                  </div>
                  <div class="ability-item">
                    <span class="ability-label">信用值</span>
                    <el-progress :percentage="leader.credit || 0" :format="format" :stroke-width="8" :color="creditColor"></el-progress>
                  </div>
                </div>
              </div>
              
              <div class="leader-card-footer">
                <el-button size="small" type="info" @click="viewLeaderDetails(leader.user_id)" class="detail-btn">
                  <el-icon><DataAnalysis /></el-icon> 查看详情
                </el-button>
                <el-button 
                  v-if="!groupId" 
                  size="small" 
                  type="primary" 
                  @click="openApplicationModal(leader.user_id)"
                  class="apply-btn"
                >
                  <el-icon><Select /></el-icon> 选择该组长
                </el-button>
                <el-button
                  v-else
                  size="small"
                  disabled
                  class="joined-btn"
                >
                  <el-icon><Check /></el-icon> 已加入小组
                </el-button>
              </div>
            </el-card>
          </div>
          
          <div class="section-footer">
            <el-button type="primary" @click="fetchTaskLeaders" class="refresh-btn">
              <el-icon><Refresh /></el-icon> 刷新组长列表
            </el-button>
          </div>
        </div>

        <!-- 查看成员页面 -->
        <div v-if="activeSection === 'members'" class="section">
          <div class="section-header">
            <h2>本组成员</h2>
          </div>
          
          <el-empty v-if="members.length === 0" description="您尚未加入小组" />
          
          <div v-else class="member-list">
            <el-card
              v-for="member in members"
              :key="member.user_id"
              class="member-card"
              shadow="hover"
            >
              <div class="member-info">
                <el-avatar :size="40" icon="el-icon-user">{{ member.username.charAt(0) }}</el-avatar>
                <div class="member-details">
                  <h4>{{ member.username }}</h4>
                  <p class="member-id">ID: {{ member.user_id }}</p>
                </div>
              </div>
            </el-card>
          </div>
          
          <div class="section-footer">
            <el-button type="primary" @click="fetchGroupMembers" class="refresh-btn">
              <el-icon><Refresh /></el-icon> 刷新成员列表
            </el-button>
          </div>
        </div>
      </div>
    </el-main>

    <!-- 组员申请模态框 -->
    <el-dialog v-model="isApplicationModalVisible" title="发送组队申请" width="30%" center custom-class="custom-dialog">
      <div class="application-form">
        <p class="dialog-description">请介绍自己的技能和经验，帮助组长了解您的优势</p>
        <el-input
          type="textarea"
          v-model="applicationText"
          placeholder="请输入申请相关介绍或简历"
          :rows="5"
          maxlength="500"
          show-word-limit
        ></el-input>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isApplicationModalVisible = false">取消</el-button>
          <el-button type="primary" @click="submitApplication" :disabled="!applicationText.trim()">
            <el-icon><Check /></el-icon> 提交申请
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 组长能力详情模态框 -->
    <el-dialog v-model="isLeaderDetailModalVisible" title="组长能力详情" width="50%" center custom-class="custom-dialog leader-detail-dialog">
      <div v-if="leaderDetails" class="leader-details-container">
        <div class="leader-profile">
          <div class="leader-avatar">
            <el-avatar :size="80" icon="el-icon-user-solid">{{ leaderDetails.username?.charAt(0) }}</el-avatar>
          </div>
          <div class="leader-basic-info">
            <h2>{{ leaderDetails.username }}</h2>
            <div class="leader-id">ID: {{ leaderDetails.user_id }}</div>
            <div class="leader-experience">
              <el-tag size="small" effect="dark" type="success">已完成 {{ leaderDetails.times }} 次任务</el-tag>
            </div>
          </div>
        </div>
        
        <el-divider content-position="center">能力指标</el-divider>
        
        <div class="leader-stats">
          <div class="stat-grid">
            <div class="stat-item">
              <div class="stat-label">能力值</div>
              <el-progress type="dashboard" :percentage="leaderDetails.ability" :color="abilityColor" :stroke-width="10"></el-progress>
            </div>
            <div class="stat-item">
              <div class="stat-label">参与积极性</div>
              <el-progress type="dashboard" :percentage="leaderDetails.enthusiasm" :color="enthusiasmColor" :stroke-width="10"></el-progress>
            </div>
            <div class="stat-item">
              <div class="stat-label">表达能力</div>
              <el-progress type="dashboard" :percentage="leaderDetails.communication" :color="communicationColor" :stroke-width="10"></el-progress>
            </div>
            <div class="stat-item">
              <div class="stat-label">人气</div>
              <el-progress type="dashboard" :percentage="leaderDetails.popularity" :color="popularityColor" :stroke-width="10"></el-progress>
            </div>
            <div class="stat-item">
              <div class="stat-label">信用</div>
              <el-progress type="dashboard" :percentage="leaderDetails.credit" :color="creditColor" :stroke-width="10"></el-progress>
            </div>
          </div>
        </div>
        
        <el-divider content-position="center">能力雷达图</el-divider>
        
        <!-- 图表展示区域 -->
        <div id="leaderChart" class="chart-container"></div>
      </div>
      <div v-else class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isLeaderDetailModalVisible = false">关闭</el-button>
          <el-button type="primary" @click="isLeaderDetailModalVisible = false">
            <el-icon><Check /></el-icon> 确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-container>
</template>

<script>
import { defineComponent, ref, onMounted, nextTick, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  ElContainer,
  ElAside,
  ElMain,
  ElMenu,
  ElMenuItem,
  ElCard,
  ElButton,
  ElDialog,
  ElInput,
  ElAvatar,
  ElTag,
  ElProgress,
  ElDivider,
  ElEmpty,
  ElSkeleton,
  ElIcon,
} from "element-plus";
import {
  UserFilled,
  User,
  DataAnalysis,
  Select,
  Check,
  Refresh,
} from "@element-plus/icons-vue";
import axios from "@/axiosInstance";
import * as echarts from "echarts";

export default defineComponent({
  name: "TeamApplicantPage",
  components: {
    ElContainer,
    ElAside,
    ElMain,
    ElMenu,
    ElMenuItem,
    ElCard,
    ElButton,
    ElDialog,
    ElInput,
    ElAvatar,
    ElTag,
    ElProgress,
    ElDivider,
    ElEmpty,
    ElSkeleton,
    ElIcon,
    UserFilled,
    User,
    DataAnalysis,
    Select,
    Check,
    Refresh,
  },
  setup() {
    const router = useRouter();
    const route = useRoute();

    // 从路由 query 中获取参数（注意大小写与前一页面一致）
    const taskId = ref(route.query.taskId);
    const groupId = ref(route.query.groupId || ""); // 若尚未加入小组，groupId 可能为空
    const sysUserId = ref(route.query.UserId);
    const sysUserName = ref(route.query.sysUserName);

    // 当前激活的侧边栏选项
    const activeSection = ref("leaders");

    // 搜索查询
    const searchQuery = ref("");

    // 组长列表数据
    const leaders = ref([]);
    // 当前组成员名单（仅当已加入小组时）
    const members = ref([]);
    
    // 过滤后的组长列表
    const filteredLeaders = computed(() => {
      if (!searchQuery.value) return leaders.value;
      const query = searchQuery.value.toLowerCase();
      return leaders.value.filter(leader => 
        leader.username.toLowerCase().includes(query) ||
        String(leader.user_id).includes(query)
      );
    });

    // 申请模态框控制
    const isApplicationModalVisible = ref(false);
    const applicationText = ref("");
    const selectedLeaderId = ref(null);

    // 组长详情模态框控制与数据
    const isLeaderDetailModalVisible = ref(false);
    const leaderDetails = ref(null);
    const applicantCount = ref(0);

    // 获取任务组长列表，调用后端 GET /api/task-leaders/<taskId>/leaders/
    const fetchTaskLeaders = async () => {
      try {
        console.log("获取组长列表，任务ID:", taskId.value);
        const response = await axios.get(`http://39.105.217.183:8000/tasks/${taskId.value}/leaders/`);
        if (response.data.status === "success") {
          leaders.value = response.data.data;
          console.log("组长名单:", leaders.value);
        } else {
          console.error("获取组长名单失败:", response.data.message);
        }
      } catch (error) {
        console.error("获取组长信息失败：", error);
      }
    };

    // 获取当前小组成员名单（调用 GET /api/score/group_members/），若 groupId 为空则不调用
    const fetchGroupMembers = async () => {
      console.log("获取小组成员，任务ID:", taskId.value, "小组ID:", groupId.value);
      if (!groupId.value) {
        members.value = [];
        return;
      }
      try {
        const response = await axios.get("http://39.105.217.183:8000/api/score/group_members/", {
          params: {
            task_id: taskId.value,
            group_id: groupId.value,
          },
        });
        console.log("小组成员列表：", response.data);
        members.value = response.data; // 假设返回数组
      } catch (error) {
        console.error("获取小组成员失败：", error);
      }
    };

    // 打开申请模态框（选择组长）
    const openApplicationModal = (selectedId) => {
      selectedLeaderId.value = selectedId;
      isApplicationModalVisible.value = true;
      console.log("打开申请模态框，选中的组长ID:", selectedId);
    };

    // 提交组队申请，调用 POST /api/submit-application/
    const submitApplication = async () => {
      console.log("提交申请：",taskId.value, sysUserId.value, selectedLeaderId.value, applicationText.value);
      try {
        const payload = {
          task_id: taskId.value,
          leader_id: selectedLeaderId.value,
          applicant_id: sysUserId.value, // 当前组员的ID
          application_text: applicationText.value,
        };
        const response = await axios.post("http://39.105.217.183:8000/api/submit-application/", payload);
        alert("申请提交成功！");
        isApplicationModalVisible.value = false;
        applicationText.value = "";
      } catch (error) {
        console.error("发送申请失败：", error);
        alert("发送申请失败！");
      }
    };

    // 查看组长能力详情：调用 GET /api/leader-details/?leader_id=...
    const viewLeaderDetails = async (leaderIdParam) => {
      try {
        const response = await axios.get("http://39.105.217.183:8000/api/leader-details/", {
          params: { leader_id: leaderIdParam },
        });
        leaderDetails.value = response.data;
        nextTick(() => {
          initLeaderChart();
        });
        isLeaderDetailModalVisible.value = true;
      } catch (error) {
        console.error("获取组长详情失败：", error);
      }
    };

    // 格式化进度条显示
    const format = (percentage) => {
      return percentage ? `${percentage}%` : '0%';
    };
    
    // 颜色计算函数
    const getColorByPercentage = (percentage) => {
      if (percentage >= 80) return '#67C23A';
      if (percentage >= 60) return '#409EFF';
      if (percentage >= 40) return '#E6A23C';
      return '#F56C6C';
    };
    
    // 各项能力的颜色
    const abilityColor = computed(() => getColorByPercentage(leaderDetails.value?.ability || 0));
    const enthusiasmColor = computed(() => getColorByPercentage(leaderDetails.value?.enthusiasm || 0));
    const communicationColor = computed(() => getColorByPercentage(leaderDetails.value?.communication || 0));
    const popularityColor = computed(() => getColorByPercentage(leaderDetails.value?.popularity || 0));
    const creditColor = computed(() => getColorByPercentage(leaderDetails.value?.credit || 0));
    
    // 利用 ECharts 绘制组长能力图表（雷达图）
    const initLeaderChart = () => {
      const chartDom = document.getElementById("leaderChart");
      if (!chartDom || !leaderDetails.value) return;
      const myChart = echarts.init(chartDom);
      console.log("绘制图表：", leaderDetails.value);
      
      const option = {
        title: {
          text: '组长能力雷达图',
          textStyle: {
            fontSize: 16,
            fontWeight: 'normal'
          }
        },
        tooltip: {},
        legend: {
          data: [leaderDetails.value.username],
          right: 0,
          top: 0
        },
        radar: {
          indicator: [
            { name: '能力值', max: 100 },
            { name: '参与积极性', max: 100 },
            { name: '表达能力', max: 100 },
            { name: '人气', max: 100 },
            { name: '信用', max: 100 }
          ],
          radius: '65%',
          splitArea: {
            areaStyle: {
              color: ['rgba(114, 172, 209, 0.05)', 'rgba(114, 172, 209, 0.1)']
            }
          }
        },
        series: [{
          name: '能力指标',
          type: 'radar',
          data: [{
            value: [
              leaderDetails.value.ability,
              leaderDetails.value.enthusiasm,
              leaderDetails.value.communication,
              leaderDetails.value.popularity,
              leaderDetails.value.credit
            ],
            name: leaderDetails.value.username,
            areaStyle: {
              color: 'rgba(64, 158, 255, 0.3)'
            },
            lineStyle: {
              width: 2
            },
            itemStyle: {
              color: '#409EFF'
            }
          }]
        }]
      };
      
      myChart.setOption(option);
      
      // 窗口大小变化时重新调整图表大小
      window.addEventListener('resize', () => {
        myChart.resize();
      });
    };

    onMounted(() => {
      console.log("参数：", taskId.value, groupId.value, sysUserId.value, sysUserName.value);
      fetchTaskLeaders();
      fetchGroupMembers();
    });

    return {
      activeSection,
      searchQuery,
      leaders,
      members,
      filteredLeaders,
      isApplicationModalVisible,
      applicationText,
      isLeaderDetailModalVisible,
      leaderDetails,
      applicantCount,
      fetchTaskLeaders,
      fetchGroupMembers,
      openApplicationModal,
      submitApplication,
      viewLeaderDetails,
      format,
      abilityColor,
      enthusiasmColor,
      communicationColor,
      popularityColor,
      creditColor,
    };
  },
});
</script>

<style scoped>
.team-applicant-container {
  min-height: 100vh;
  display: flex;
  background-color: #f5f7fa;
}

/* 侧边栏样式 */
.sidebar {
  width: 220px;
  background-color: #ffffff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 10;
  transition: all 0.3s;
}

.logo-container {
  padding: 20px 0;
  text-align: center;
  border-bottom: 1px solid #f0f0f0;
}

.app-title {
  margin: 0;
  color: #409EFF;
  font-size: 20px;
  font-weight: 600;
}

.menu {
  border-right: none;
  padding: 10px 0;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 0 20px;
}

/* 内容区样式 */
.content {
  padding: 20px;
  flex: 1;
  display: flex;
  justify-content: center;
  overflow-y: auto;
}

.board {
  width: 900px;
  background-color: transparent;
  padding: 0;
}

.section {
  background-color: #ffffff;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 30px;
  transition: all 0.3s;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.search-input {
  width: 250px;
}

.section-footer {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 组长卡片样式 */
.leader-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.leader-card {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
}

.leader-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.leader-card-header {
  padding: 20px;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
}

.avatar-container {
  margin-right: 15px;
}

.leader-info {
  flex: 1;
}

.leader-info h3 {
  margin: 0 0 5px 0;
  font-size: 18px;
  color: #303133;
}

.leader-tags {
  display: flex;
  gap: 5px;
}

.leader-card-body {
  padding: 15px 20px;
}

.ability-preview {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.ability-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.ability-label {
  font-size: 14px;
  color: #606266;
}

.leader-card-footer {
  padding: 15px 20px;
  background-color: #f5f7fa;
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #ebeef5;
}

.detail-btn, .apply-btn, .joined-btn {
  transition: all 0.3s;
}

.detail-btn:hover, .apply-btn:hover {
  transform: scale(1.05);
}

/* 成员列表样式 */
.member-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.member-card {
  border-radius: 8px;
  transition: all 0.3s;
}

.member-info {
  display: flex;
  align-items: center;
  padding: 10px;
}

.member-details {
  margin-left: 15px;
}

.member-details h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
  color: #303133;
}

.member-id {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

/* 对话框样式 */
.custom-dialog {
  border-radius: 8px;
}

.dialog-description {
  margin-bottom: 15px;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 组长详情模态框样式 */
.leader-details-container {
  padding: 10px;
}

.leader-profile {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.leader-avatar {
  margin-right: 20px;
}

.leader-basic-info {
  flex: 1;
}

.leader-basic-info h2 {
  margin: 0 0 5px 0;
  font-size: 22px;
  color: #303133;
}

.leader-id {
  margin-bottom: 10px;
  font-size: 14px;
  color: #909399;
}

.leader-experience {
  margin-top: 10px;
}

.stat-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 20px;
  margin: 20px 0;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.stat-label {
  margin-bottom: 10px;
  font-size: 16px;
  color: #606266;
}

.chart-container {
  width: 100%;
  height: 400px;
  margin: 20px 0;
}

.loading-container {
  padding: 20px;
}

.notification-badge {
  background-color: #ff4444;
  color: #fff;
  border-radius: 50%;
  padding: 2px 6px;
  font-size: 12px;
  margin-left: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .leader-grid {
    grid-template-columns: 1fr;
  }
  
  .stat-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .sidebar {
    width: 180px;
  }
  
  .board {
    width: 100%;
  }
}

</style>